import React, { Component, Fragment } from "react";
// propTypes
import PropTypes from 'prop-types';
// antd
import { message, Modal, Row, Col, Table, Radio, Form } from "antd";
// api
import { TableList, TableDelete } from "@api/common";
import http from '../../utils/request';
// url
import requestUrl from "@api/requestUrl";
// Table basis component
import TableBasis from "./Table";
// import TableNested from "./NestTable";
import FormSearch from "../formSearch/Index";

const options_status = [
    { label: "开启", value: true },
    { label: "关闭", value: false }
];
const options_month = [
    { label: "1", value: 1 },
    { label: "2", value: 2 },
    { label: "3", value: 3 },
    { label: "4", value: 4 },
    { label: "5", value: 5 },
    { label: "6", value: 6 },
    { label: "7", value: 7 },
    { label: "8", value: 8 },
    { label: "9", value: 9 }
]
const options_year = [
    { label: "1", value: 12 },
    { label: "2", value: 24 },
    { label: "3", value: 36 }
];
class TableComponent extends Component {
    constructor(props){
        super(props);
        this.state = {
            // 请求参数
            pageNumber: 1,
            pageSize: 10,
            searchData: {},
            // 数据
            data: [],
            // 子表格数据
            dataEx: [],
            // 加载提示
            loadingTable: false,
            // 页码
            total: 0,
            // 复选框
            checkboxValue: [],
            selectedRowKeys: [],
            // 确认弹窗
            modalVisible: false,
            modalconfirmLoading: false,
            StatusModalVisible: false,
            StatusModalconfirmLoading: false,
            BatchRenewModalVisible: false,
            BatchRenewModalconfirmLoading: false,
            // status
            StatusRadioValue: '',
            // renew
            isTableloading: false,
            formLayout: {
                labelCol: { span: 2 },
                wrapperCol: { span: 22, offset: 1 }
            },
            tableColumns: [
                {
                  title: '实例ID/名称',
                  key: 'InstanceId',
                  dataIndex: 'InstanceId',
                  render: (text, rowData) => {
                    return (
                        <div>
                            {rowData.instance_id}
                            <br></br>
                            {rowData.instance_name}
                        </div>
                    )
                  }
                },
                {
                  title: '规格',
                  dataIndex: 'instance_type',
                  key: 'instance_type',
                  render: (text, rowData) => {
                    return (
                        <div>
                            {rowData.cpu} vCPU {rowData.memory/1024} GiB
                            <br></br>
                            ({rowData.instance_type})
                        </div>
                    )
                  }
                },
                {
                    title: '到期时间',
                    key: 'expired_time',
                    dataIndex: 'expired_time',
                    render: (text, rowData) => {
                        return (
                            <div>
                                {/* {rowData.StartTime}
                                <br></br> */}
                                {rowData.expired_time}
                            </div>
                        )}
                },
                {
                    title: '价格',
                    key: 'age',
                    render: (text) => {
                        return (
                            <div>
                                <span style={{color: '#f60'}}>￥ {this.state.trade_price}</span>
                                <br/>
                                {this.state.discount_price > 0 ? <span style={{color: '#2f7d0d'}}>省: ￥ {this.state.discount_price}</span> : ''}
                            </div>
                        )}
                }
            ],
            tableData: null
        }
    }

    componentDidMount(){
        this.loadData();
        // 返回子组件实例
        this.props.onRef(this);  // 子组件调用父组件方法，并把子组件实例传回给父组件
    }

    /** 获取列表数据 */
    loadData = () => {
        const { pageNumber, pageSize, searchData } = this.state;
        const requestData = {
            url: requestUrl[this.props.config.url] ? requestUrl[this.props.config.url] : this.props.config.url,
            method: this.props.config.method,
            data: {
                page: pageNumber,
                limit: this.props.config.pageSize ? this.props.config.pageSize : pageSize,
            }
        }
        // 筛选项的参数拼接
        if(Object.keys(searchData).length !== 0) {
            for(let key in searchData) {
                requestData.data[key] = searchData[key]
            }
        }
        this.setState({loadingTable: true})
        // 请求接口
        TableList(requestData).then(response => {
            console.log(response);
            const responseData = response.data.data; // 数据
            if(responseData.items) {  // 返回一个 null
                this.setState({
                    data: responseData.items,
                    total: responseData.pages.total,
                    loadingTable: false
                })
            }
        }).catch(error => {
            this.setState({loadingTable: false})
        })
    }
    search = (searchData) => {
        this.setState({
            pageNumber: 1,
            pageSize: 10,
            searchData
        }, () => {
            this.loadData();
        })
    }
    /** 删除 */
    onHandlerDelete(id){
        console.log(id,typeof(id),typeof(id.toString().split()))
        this.setState({ modalVisible: true })
        if(id) { this.setState({ selectedRowKeys: id.toString().split() }); }  // 单个删除id
    }
    /** 批量变更 */
    onHandlerChange(id){
        this.setState({ StatusModalVisible: true })
        if(id) { this.setState({ selectedRowKeys: id }); }
    }
    /** 批量续费 */
    onHandlerRenewEcs = () => {
        this.setState({ 
            BatchRenewModalVisible: true
        }) 
    }

    /**批量变更中radio按钮 */
    onChangeRadio = (e) => {
        this.setState({ StatusRadioValue: e.target.value })
    }
    /** 复选框 */
    onCheckebox = (selectedRowKeys) => {
        this.setState({selectedRowKeys})
        console.log('onCheckebox selectedRowKeys', this.state.selectedRowKeys)
    }
    /** 当前页码 */
    onChangeCurrnePage = (value) => {
        if (value === 0) {
            value = 1
        };
        this.setState({
            pageNumber: value
        }, () => {
            this.loadData();
        })
    }
    /** 下拉页码 */
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            this.loadData()
        })
    }
    /** 批量续费确认弹窗 */
    modalThenBatchRenew = () => {
        // 判断是否已选择操作的数据
        if(this.state.selectedRowKeys.length === 0) {
            message.info("请选择需要操作的数据");
            return false;
        }
        this.setState({ BatchRenewModalconfirmLoading: true })
        const ids = this.state.selectedRowKeys
        console.log("批量变更状态提交",ids)
    }

    // 变更状态确认弹窗
    modalThenStatus = () => {
        // 判断是否已选择操作的数据
        if(this.state.selectedRowKeys.length === 0) {
            message.info("请选择需要操作的数据");
            return false;
        }
        this.setState({ StatusModalconfirmLoading: true })
        const ids = this.state.selectedRowKeys
        console.log("批量变更状态提交",ids)
        // api 
        const requestData = {
            'ids': ids,
            'value': this.state.StatusRadioValue,
            'method': 'update'
        }
        http.post('/info/postcode',requestData).then(response=>{
            message.info(response.data.msg);
            // 清空数值
            this.setState({
                StatusModalVisible: false,
                id: "",
                StatusModalconfirmLoading: false,
                selectedRowKeys: []
            })
            // 重新加载数据
            this.loadData();
        })
    }
    /** 删除确认弹窗 */
    modalThen = () => {
        // 判断是否已选择删除的数据 0 无 1 单删 >1 批量删除 
        console.log(this.state.selectedRowKeys.length)
        if(this.state.selectedRowKeys.length === 0) {
            message.info("请选择需要删除的数据");
            return false;
        }
        this.setState({ confirmLoading: true })
        const id = this.state.selectedRowKeys.join();
        // 特殊删除和查询接口不相同的情况
        const url_del = this.props.config.url_del ? this.props.config.url_del : this.props.config.url
        const requestData = {
            url: requestUrl[url_del] + "/" + id,
            method: "delete",
            data: {
                id
            }
        }
        console.log(requestData)
        TableDelete(requestData).then(response => {
            message.info(response.data.msg);
            this.setState({
                modalVisible: false,
                id: "",
                modalconfirmLoading: false,
                selectedRowKeys: []
            })
            // 重新加载数据
            this.loadData();
        })
    }

    render(){
        console.log('TableComponent======>',this.props)
        const { data, selectedRowKeys, isTableloading } = this.state
        const { thead, thead_item, checkbox, nstable, rowkey, 
                formItem, formSearchCol, formRightCol 
        } = this.props.config;

        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: this.onCheckebox
        }

        const expandedRowRender = (record,index,indent,expanded) => {  // record: dataSource循环出来的每一行的数据,作为rowKey或者其它用途
            console.log('嵌套表格数据', {thead_item}, record)
            return <Table columns={thead_item} dataSource={record.items} pagination={false} />;
        };
        // 子表格点击事件，请求接口获取数据
        // const onExpand = (expanded, record) => {
        //     console.log('子表格点击事件', expanded,record)
        //     http.request({
        //         url: '/aliyun/slb/port',
        //         params: { 'instance_id': record.LoadBalancerId }
        //     }).then(response => {
        //         console.log('==>接收到值 ', response)
        //         const data = response.data.data_account;
        //         this.setState({ 
        //           dataEx: data
        //         });
        //     })
        // }

        return (
            <Fragment>
                {/* 筛选 */}
                <Row>
                    <Col span={formSearchCol || 20}><FormSearch formItem={formItem} search={this.search} /></Col>
                    <Col span={formRightCol || 4}>
                        <div className="pull-right">
                            {this.props.children}
                        </div>
                    </Col>
                </Row>
                {/* table UI 组件 */}
                <div className="table-wrap">
                    <TableBasis 
                        columns={thead} 
                        dataSource={data} 
                        total={this.state.total} 
                        changePageCurrent={this.onChangeCurrnePage}
                        changePageSize={this.onChangeSizePage}
                        handlerDelete={() => this.onHandlerDelete()}
                        handlerChangeStatus={() => this.onHandlerChange()}
                        handlerRenewEcs={() => this.onHandlerRenewEcs()}
                        batchButton={this.props.batchButton}
                        batchStatusButton={this.props.batchStatusButton}
                        batchRenewButton={this.props.batchRenewButton}
                        rowSelection={checkbox ? rowSelection : null}
                        rowkey={rowkey}
                        loadingTable={this.state.loadingTable}
                        expandable={nstable ? {expandedRowRender} : null}
                        // expandable={nstable ? {expandedRowRender, onExpand} : null}
                    />
                </div>
                {/* 确认弹窗 */}
                <Modal
                    title="提示"
                    visible={this.state.modalVisible}
                    onOk={this.modalThen}
                    onCancel={() => { this.setState({ modalVisible: false})}}
                    okText="确认"
                    cancelText="取消"
                    confirmLoading={this.state.modalconfirmLoading}
                >
                    <p className="text-center">确定删除此信息？<strong className="color-red">删除后将无法恢复。</strong></p>
                </Modal>
                <Modal
                    title="批量变更发布码状态"
                    visible={this.state.StatusModalVisible}
                    onOk={this.modalThenStatus}
                    onCancel={() => { this.setState({ StatusModalVisible: false})}}
                    okText="确认"
                    cancelText="取消"
                    confirmLoading={this.state.StatusModalconfirmLoading}
                >
                    <p className="text-center">当前已选择id:<strong className="color-red">{selectedRowKeys.join()}</strong></p>
                    <Radio.Group
                        options={options_status}
                        onChange={this.onChangeRadio}
                        value={this.state.StatusRadioValue}
                        />
                </Modal>
                <Modal
                    title="批量续费ECS信息"
                    visible={this.state.BatchRenewModalVisible}
                    onOk={this.modalThenBatchRenew}
                    onCancel={() => { this.setState({ BatchRenewModalVisible: false})}}
                    okText="确认"
                    cancelText="取消"
                    confirmLoading={this.state.BatchRenewModalconfirmLoading}
                    width='800px'
                    // footer={null}
                >
                    {/* <Modal title="续费信息" width='800px' visible={this.state.isModalVisible} footer={null} onCancel={this.handleCancel}> */}
                    <Table columns={this.state.tableColumns} dataSource={this.state.tableData} pagination={false} loading={isTableloading}></Table>
                    <Form onFinish={this.handlerFormSubmit} {...this.state.formLayout} style={{ marginTop: '40px'}}>
                        <Form.Item label="续费时长 " name="Period">
                            <span>
                            <Radio.Group
                                options={options_month}
                                onChange={this.onChangeRadio}
                                value={this.state.radio_value}
                                optionType="button"
                                buttonStyle="solid"
                                /> 个月 
                            <Radio.Group
                                options={options_year}
                                onChange={this.onChangeRadio}
                                value={this.state.radio_value}
                                optionType="button"
                                buttonStyle="solid"
                                /> 年
                            </span>
                        </Form.Item>
                        <Form.Item label="总费用 " name="price">
                            <span>100000</span>
                        </Form.Item>
                    </Form>
                </Modal>
            </Fragment>
        )
    }
}
// 校验数据类型
TableComponent.propTypes = {
    config: PropTypes.object
}
// 默认
TableComponent.defaultProps = {
    batchButton: false
}

export default TableComponent;